<template>
    <div class="main commodity-type-attr">
        <div class="search-bar">
            <div class="form-item">
                <span class="item-title">商品类型:</span>
                <span v-text="name"></span>
            </div>
           <!-- <el-button type="success" icon="el-icon-plus" class="fr" @click="showAdd">新建</el-button>-->
        </div>
        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="名称" prop="attrName"></el-table-column>
            <el-table-column align="center" label="属性值的输入方式">
                <template slot-scope="scope">
                    <span v-text="iptTypes[scope.row.attrInputType]"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="可选值列表">
                <template slot-scope="scope">
                    <el-popover placement="top" trigger="hover">
                        <div v-html="renderValues(scope.row.attrValues)"></div>
                        <p slot="reference" class="text-ellipsis" v-text="scope.row.attrValues"></p>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column align="center" label="排序" prop="sortOrder"></el-table-column>
            <el-table-column align="center" label="是否显示">
                <template slot-scope="scope">
                    <span>{{scope.row.attrStatus == 1 ? '显示' : '不显示'}}</span>
                </template>
            </el-table-column>
            <!--<el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>-->
        </el-table>
        <!--<div class="pagination-container" v-if="total > 0">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
        </div>-->
        <el-dialog :title="editItem.id ? '编辑商品属性' : '新建商品属性'" :visible.sync="showEditPop">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="名称:" prop="attrName">
                    <el-input v-model="editItem.attrName"></el-input>
                </el-form-item>
                <!--<el-form-item label="是否多选:">
                    <el-switch
                        v-model="editItem.attrType"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                    </el-switch>
                </el-form-item>-->
                <el-form-item label="值的输入方式:">
                    <!--<el-select v-model="editItem.attrInputType">
                        <el-option v-for="(name, val) in iptTypes" :key="val" :label="name" :value="val"></el-option>
                    </el-select>-->
                    <span>选择输入</span>
                </el-form-item>
                <el-form-item label="可选值列表:" prop="attrValues">
                    <el-input type="textarea" v-model="editItem.attrValues"></el-input>
                    <p class="form-tip-text">注: 一行代表一个可选值</p>
                </el-form-item>
                <el-form-item label="排序:">
                    <el-input v-model="editItem.sortOrder" type="number"></el-input>
                </el-form-item>
                <el-form-item label="是否显示:">
                    <el-switch
                        v-model="editItem.attrStatus"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :disabled="btnDisabled">保存</el-button>
                <el-button @click="showEditPop = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getAttrByTypeId} from '@/api/common'

    export default {
        name: 'commodityTypeAttr',
        props: {
            id: {
                default: ''
            },
            name: {
                default: ''
            }
        },
        data() {
            const validTypeName = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('不能为空'));
                }
                if (this.editItem.id && this.editName === value) {
                    return callback();
                }
                if (/[^\a-zA-Z0-9\u4e00-\u9FA5\-.]/.test(value)) {
                    return callback(new Error('不能含有特殊字符'));
                }
                if (value.length > 100) {
                    return callback(new Error('不能超过100字符'));
                }
                this.btnDisabled = true;
                this.request({
                    url: '/bsnl-product/attribute/name',
                    method: 'get',
                    params: {
                        name: value,
                        typeId: this.id
                    }
                }).then(({data}) => {
                    if (data && data.id) {
                        callback(new Error('类型名已存在'));
                    } else {
                        this.btnDisabled = false;
                        callback();
                    }
                }).catch(err => {
                    this.btnDisabled = false;
                    callback(new Error(err));
                });
            };
            const validAttrValue = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('不能为空'));
                }
                let temp = this.editItem.attrValues.split('\n');
                let hash = {};
                for(let i in temp) {
                    if(hash[temp[i]])
                        return callback(new Error('可选值不能重复'));
                    hash[temp[i]] = true;
                }
                return callback();
            };
            return {
                list: [],
                page: 1,
                pageSize: 999,
                total: 0,
                editItem: {},
                editName: '',
                editRule: {
                    attrName: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        {max: 100, message: '不能超过100字符', trigger: 'change'},
                        {pattern: /[\a-zA-Z0-9\u4e00-\u9FA5\-.]+$/, message: '不能含有特殊字符', trigger: 'change'},
                        {validator: validTypeName, trigger: 'blur'}
                    ],
                    attrValues: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        {validator: validAttrValue, trigger: 'change'},
                    ]
                },
                iptTypes: {
                    0: '手动输入',
                    1: '选择输入',
                    2: '多行文本输入'
                },
                showEditPop: false,
                listLoading: false,
                btnDisabled: false,
            }
        },
        created() {
            this.getList();
        },
        methods: {
            // 获取列表
            getList() {
                this.listLoading = true;
                getAttrByTypeId({
                    isPage: 0,
                    pageIndex: this.page,
                    pageSize: this.pageSize,
                    goodsTypeId: this.id
                }).then(({data, totalCount}) => {
                    this.list = data;
                    this.total = totalCount;
                    this.listLoading = false;
                }).catch(err => {
                    console.log(err);
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
            },
            renderValues(str) {
                return `<p>${str.replace(/\n/g, '</p><p>')}</p>`
            },
            // 删除
            del(item) {
                this.$confirm(`确定要删除 ${item.attrName} 吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.request({
                        url: '/bsnl-product/attribute/delete',
                        method: 'post',
                        data: {
                            id: item.id,
                            deleteFlag: 0
                        }
                    }).then(() => {
                        if (this.page > 1 && this.list.length === 1) {
                            this.page--;
                        }
                        this.getList();
                        this.$message.success('删除成功');
                    }).catch(err => {
                        console.log(err);
                        this.list = [];
                        this.total = 0;
                        this.listLoading = false;
                    });
                }).catch(err => {
                    console.log(err);
                });
            },
            // 显示新建
            showAdd() {
                this.editItem = {
                    attrName: '',
                    attrType: 0,
                    attrValues: '',
                    attrStatus: 0,
                    typeId: this.id,
                    attrInputType: 1,
                    sortOrder: ''
                };
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            // 显示编辑
            showEdit(item) {
                this.editItem = {...item};
                this.editName = item.attrName;
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            // 保存
            save() {
                this.$refs.editItem.validate(valid => {
                    if (!valid) {
                        return false;
                    }
                    const {
                        id,
                        attrName,
                        attrType,
                        attrValues,
                        attrStatus,
                        typeId,
                        attrInputType,
                        sortOrder
                    } = this.editItem;
                    let url = id ? '/bsnl-product/attribute/update' : '/bsnl-product/attribute/create';
                    this.btnDisabled = true;
                    this.request({
                        url,
                        method: 'post',
                        data: {
                            id,
                            attrName,
                            attrType,
                            attrValues,
                            attrStatus,
                            typeId,
                            attrInputType,
                            sortOrder
                        }
                    }).then(() => {
                        this.btnDisabled = false;
                        this.editItem = {};
                        this.showEditPop = false;
                        this.$message.success('保存成功');
                        this.getList();
                    }).catch(err => {
                        this.btnDisabled = false;
                    });
                });
            },
            // 搜索
            search() {
                this.page = 1;
                this.query = {
                    ...this.params
                };
                this.getList();
            },
            // 切换分页
            handleCurrentChange(page) {
                this.page = page;
                this.getList();
            },
        }
    }
</script>
